package com.ge.common.interceptor;

import com.ge.common.annotation.TechnicianAuthIgnoreApi;
import com.ge.common.exception.RRException;
import com.ge.modules.api.service.TbTechnicianTokenService;
import com.ge.modules.entity.TbTechnicianToken;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** 权限(Token)验证
 *
 * @author wuye
 * @date 2018/1/15
 */
@Component
public class TechnicianAuthorizationInterceptorApi extends HandlerInterceptorAdapter {

    @Autowired
    private TbTechnicianTokenService technicianTokenService;

    public static final String TECHNICIAN_KEY = "LOGIN_TECHNICIAN_KEY_API";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        TechnicianAuthIgnoreApi annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(TechnicianAuthIgnoreApi.class);
        }else{
            return true;
        }

        //如果有@IgnoreAuth注解，则不验证token
        if(annotation != null){
            return true;
        }

        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }

        //token为空
        if(StringUtils.isBlank(token)){
            //设置换回编码为501 登录需要登录或者登录失效
            throw new RRException("token不能为空",501);
        }

        //查询token信息
        TbTechnicianToken tokenEntity = technicianTokenService.queryByToken(token);
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            //设置换回编码为501 登录需要登录或者登录失效
            throw new RRException("token失效，请重新登录",501);
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(TECHNICIAN_KEY, tokenEntity.getTechnicianId());

        return true;
    }
}
